package com.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.store.configure.Result;
import com.store.entity.User;
import com.store.mapper.UserMapper;
import com.store.service.LoginService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Service
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements LoginService {

    @Resource
    UserMapper userMapper;


    @Override
    public Result<User> login(User user, HttpServletRequest request) {
        Result<User> result = new Result<>();
        try {
            if (StringUtils.isEmpty(user.getUserAccount()) || StringUtils.isEmpty(user.getUserPassword())) {
                result.setMessage("用户名密码不能为空");
                return result;
            }

            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(User::getUserAccount, user.getUserAccount());
            wrapper.lambda().eq(User::getUserPassword, user.getUserPassword());

            List<User> userList = userMapper.selectList(wrapper);
            if (userList != null && userList.size() == 1) {
                HttpSession session = request.getSession();
                session.setAttribute("loginUser", userList.get(0));
                result.setMessage("success");
                result.setReturnObj(userList.get(0));
            } else if (userList != null && userList.size() > 1) {
                result.setMessage("账号出现重复，清询问系统管理员");
            } else {
                result.setMessage("用户名密码错误");
            }
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<User> logout(HttpServletRequest request) {
        Result<User> result = new Result<>();
        HttpSession session = request.getSession();
        session.removeAttribute("loginUser");
        result.setMessage("success");
        return result;
    }
}
